/**
 * Copyright 2014-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.webank.fiscobcoscanal1.manager;

import java.io.IOException;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;

import org.bcos.web3j.protocol.Web3j;
import org.bcos.web3j.protocol.core.DefaultBlockParameter;
import org.bcos.web3j.protocol.core.methods.response.EthBlock.Block;
import org.bcos.web3j.protocol.core.methods.response.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.webank.fiscobcoscanal1.db.entity.BlockInfo;
import com.webank.fiscobcoscanal1.db.entity.BlockTaskPool;
import com.webank.fiscobcoscanal1.db.entity.TransactionInfo;
import com.webank.fiscobcoscanal1.db.repository.BlockInfoRepository;
import com.webank.fiscobcoscanal1.db.repository.TransactionInfoRepository;

import lombok.extern.slf4j.Slf4j;

/**
 * TransactionExportManager
 *
 * @Description: TransactionExportManager
 * @author maojiayu
 * @data Oct 30, 2019 2:26:44 PM
 *
 */
@Service
@Slf4j
public class TransactionExportManager {
    @Autowired
    private Web3j web3j;
    @Autowired
    private BlockInfoRepository blockInfoRepository;
    @Autowired
    private TransactionInfoRepository transactionInfoRepository;

    public void export(List<BlockTaskPool> taskPool) throws IOException {
        List<BlockInfo> blockInfos = Lists.newArrayList();
        List<TransactionInfo> transactionInfos = Lists.newArrayList();
        for (BlockTaskPool task : taskPool) {
            Block block = web3j.ethGetBlockByNumber(DefaultBlockParameter.valueOf(task.getBlockHeight()), false).send()
                    .getBlock();
            BlockInfo blockInfo = new BlockInfo();
            blockInfo.setBlockHash(block.getHash()).setBlockHeight(task.getBlockHeight())
                    .setBlockTimeStamp(new Date(block.getTimestamp().longValue()))
                    .setTxCount(block.getTransactions().size());
            blockInfos.add(blockInfo);
            // for transactions
            for (int i = 0; i < block.getTransactions().size(); i++) {
                TransactionInfo ti = new TransactionInfo();
                Transaction et =
                        web3j.ethGetTransactionByBlockNumberAndIndex(DefaultBlockParameter.valueOf(block.getNumber()),
                                BigInteger.valueOf(i)).send().getResult();
                ti.setBlockHeight(block.getNumber()).setIndexNumber(i).setData(et.getInput()).setValue(et.getValueRaw())
                        .setFrom(et.getFrom()).setTo(et.getTo());
                if (et.getTo() == null) {
                    ti.setTo("");
                }
                transactionInfos.add(ti);
            }
        }
        log.info("Begin to save export result, tx size: {}", transactionInfos.size());
        blockInfoRepository.saveAll(blockInfos);
        transactionInfoRepository.saveAll(transactionInfos);
    }

}
